#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <curl/curl.h>

#define NUM_THREADS 4 // 定义线程数量

// 结构体用于传递参数给线程
struct ThreadData {
    char *url;
    char *filename;
};

// 下载图片的函数
void *download_image(void *threadarg) {
    struct ThreadData *my_data;
    my_data = (struct ThreadData *) threadarg;
    
    CURL *curl;
    FILE *fp;
    CURLcode res;
    
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(my_data->filename, "wb");
        if (fp == NULL) {
            fprintf(stderr, "Failed to open file: %s\n", my_data->filename);
            pthread_exit(NULL);
        }
        
        curl_easy_setopt(curl, CURLOPT_URL, my_data->url);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    
    pthread_exit(NULL);
}

int main() {
    CURL *curl;
    pthread_t threads[NUM_THREADS];
    struct ThreadData td[NUM_THREADS];
    int rc, i;
    
    // 初始化 libcurl
    curl_global_init(CURL_GLOBAL_ALL);
    
    // 创建多个线程进行图片下载
    for (i = 0; i < NUM_THREADS; i++) {
        td[i].url = "https://example.com/image.jpg"; // 图片的 URL
        char filename[20];
        sprintf(filename, "image%d.jpg", i); // 图片文件名
        td[i].filename = strdup(filename);
        rc = pthread_create(&threads[i], NULL, download_image, (void *)&td[i]);
        if (rc) {
            fprintf(stderr, "Error: pthread_create() failed\n");
            exit(-1);
        }
    }
    
    // 等待所有线程结束
    for (i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    
    // 清理资源
    curl_global_cleanup();
    
    return 0;
}

